//
//  HOJPushHandler.m
//  WeiDu
//
//  Created by foguo-mac-1 on 23/11/2017.
//  Copyright © 2017 WeiDu. All rights reserved.
//

#import "HOJPushHandler.h"
#import "HOAppController.h"
#import "HOAppDataModule.h"
#import "HOGlobalData.h"
#ifdef NSFoundationVersionNumber_iOS_9_x_Max
#import <UserNotifications/UserNotifications.h>
#import <UserNotificationsUI/UserNotificationsUI.h>
#endif

#import "Logger.h"
#import "HOUIMgr.h"



static HOJPushHandler *_instance;
@implementation HOJPushHandler
+ (HOJPushHandler *)sharedInstance
{
	if(_instance == nil)
	{
		_instance = [[HOJPushHandler alloc] init];
		
	}

	return _instance;
}

- (void)setBadge:(NSInteger)number
{
	[JPUSHService setBadge:number];
}

- (void)openPushNotification:(BOOL)open
{
	if(open)
	{
		
		[HOGlobalData sharedInstance].isPopedUpAlertForNotifaction = NO;
		[HOJPushHandler sharedInstance].isNotificationOpened = YES;
		// Required
		if (IS_MORETHAN_IOS8)
		{
			//可以添加自定义categories
			[JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
															  UIUserNotificationTypeSound |
															  UIUserNotificationTypeAlert)
												  categories:nil];
		}
		else
		{
			//categories 必须为nil
			[JPUSHService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
															  UIRemoteNotificationTypeSound |
															  UIRemoteNotificationTypeAlert)
												  categories:nil];
		}
		
		
	}
	else
	{
		[HOJPushHandler sharedInstance].isNotificationOpened = NO;
		[[UIApplication sharedApplication] unregisterForRemoteNotifications];
		
	}
	
	
}

- (void)togglePushNotification
{
	//Handle push notification
	[HOJPushHandler sharedInstance].isNotificationOpened = ![HOJPushHandler sharedInstance].isNotificationOpened;
	[self openPushNotification:[HOJPushHandler sharedInstance].isNotificationOpened];
}


- (void)registerJPushServiceWithOptions:(NSDictionary *)launchOptions
{
	//Required
	//notice: 3.0.0及以后版本注册可以这样写，也可以继续用之前的注册方式
	//	[JPUSHService setDebugMode];
	
	JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
	entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
	//if (IS_MORETHAN_IOS8) {
	// 可以添加自定义categories
	// NSSet<UNNotificationCategory *> *categories for iOS10 or later
	// NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
	//}
	[JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
}

- (void)initJPushServiceWithOptions:(NSDictionary *)launchOptions
{
	// Optional
	// 获取IDFA
	// 如需使用IDFA功能请添加此代码并在初始化方法的advertisingIdentifier参数中填写对应值
	//NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
	
	// Required
	// init Push
	// notice: 2.1.5版本的SDK新增的注册方法，改成可上报IDFA，如果没有使用IDFA直接传nil
	// 如需继续使用pushConfig.plist文件声明appKey等配置内容，请依旧使用[JPUSHService setupWithOption:launchOptions]方式初始化。
//	NSLog(@"mIsProduction:%@", mIsProduction ? @"YES":@"NO");
//	NSLog(@"mJPushAppKey:%@", mJPushAppKey);
//	NSLog(@"mChannel:%@", mChannel);
	[JPUSHService setupWithOption:launchOptions appKey:mJPushAppKey
						  channel:mChannel
				 apsForProduction:mIsProduction
			advertisingIdentifier:nil];
	
	//2.1.9版本新增获取registration id block接口。
	[JPUSHService registrationIDCompletionHandler:^(int resCode, NSString *registrationID) {
		if(resCode == 0){
			
//			NSLog(@"registrationID获取成功：%@",registrationID);
			self.jPushRegistrationID = registrationID;
//			LogInf(@"jpushId:%@", registrationID);
			if(registrationID == nil)
				return;
			[[HOUIMgr sharedInstance] didGetJPushRegistrationID:registrationID];
			
		}
		else{
//			NSLog(@"registrationID获取失败，code：%d",resCode);
		}
	}];
}

#pragma mark - -- JPush notificatio
- (void)addObserveJPushNotifications
{
	NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
	[defaultCenter addObserver:self
					  selector:@selector(networkDidSetup:)
						  name:kJPFNetworkDidSetupNotification
						object:nil];
	[defaultCenter addObserver:self
					  selector:@selector(networkDidClose:)
						  name:kJPFNetworkDidCloseNotification
						object:nil];
	[defaultCenter addObserver:self
					  selector:@selector(networkDidRegister:)
						  name:kJPFNetworkDidRegisterNotification
						object:nil];
	[defaultCenter addObserver:self
					  selector:@selector(networkDidLogin:)
						  name:kJPFNetworkDidLoginNotification
						object:nil];
	[defaultCenter addObserver:self
					  selector:@selector(networkDidReceiveMessage:)
						  name:kJPFNetworkDidReceiveMessageNotification
						object:nil];
	[defaultCenter addObserver:self
					  selector:@selector(serviceError:)
						  name:kJPFServiceErrorNotification
						object:nil];
}

- (void)removeObserveJPushNotifications
{
	NSNotificationCenter *defaultCenter = [NSNotificationCenter defaultCenter];
	[defaultCenter removeObserver:self
							 name:kJPFNetworkDidSetupNotification
						   object:nil];
	[defaultCenter removeObserver:self
							 name:kJPFNetworkDidCloseNotification
						   object:nil];
	[defaultCenter removeObserver:self
							 name:kJPFNetworkDidRegisterNotification
						   object:nil];
	[defaultCenter removeObserver:self
							 name:kJPFNetworkDidLoginNotification
						   object:nil];
	[defaultCenter removeObserver:self
							 name:kJPFNetworkDidReceiveMessageNotification
						   object:nil];
	[defaultCenter removeObserver:self
							 name:kJPFServiceErrorNotification
						   object:nil];
}

- (void)serviceError:(NSNotification *)notification {
	NSDictionary *userInfo = [notification userInfo];
	NSString *error = [userInfo valueForKey:@"error"];
	LogInf(@"JSPush serviceError%@", error);
}
- (void)networkDidSetup:(NSNotification *)notification {
	LogInf(@"JSPush networkDidSetup");
}

- (void)networkDidClose:(NSNotification *)notification {
	LogInf(@"JSPush networkDidClose");
}

- (void)networkDidRegister:(NSNotification *)notification
{
	LogInf(@"JSPush [JPUSHService getjpushid]:%@", [JPUSHService registrationID]);
	
	[self didGetJPushRegistrationID:[JPUSHService registrationID]];
}

- (void)networkDidLogin:(NSNotification *)notification {
	
	LogInf(@"JSPush [JPUSHService jpushId]:%@", [JPUSHService registrationID]);
	[self didGetJPushRegistrationID:[JPUSHService registrationID]];
}

- (void)didGetJPushRegistrationID:(NSString *)jid
{
	self.jPushRegistrationID = jid;
	LogInf(@"jpushId:%@", jid);
	if(jid == nil)
		return;
	[[HOUIMgr sharedInstance] didGetJPushRegistrationID:jid];
}

- (void)networkDidReceiveMessage:(NSNotification *)notification {
	
	[[HOUIMgr sharedInstance] networkDidReceiveMessage:notification];
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
	// Required
	NSDictionary * userInfo = notification.request.content.userInfo;
	if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
		[JPUSHService handleRemoteNotification:userInfo];
	}
	completionHandler(UNNotificationPresentationOptionAlert); // 需要执行这个方法，选择是否提醒用户，有Badge、Sound、Alert三种类型可以选择设置
}

// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)(void))completionHandler {
	// Required
	NSDictionary * userInfo = response.notification.request.content.userInfo;
	if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
		[JPUSHService handleRemoteNotification:userInfo];
	}
	completionHandler();  // 系统要求执行这个方法
}
- (NSString *)getRegistertationID
{
	if(self.jPushRegistrationID == nil || self.jPushRegistrationID.length == 0)
	{
		return [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
	}
	return self.jPushRegistrationID;
}

- (void)cleanup
{
	[self removeObserveJPushNotifications];
}

@end
